package com.plum.admin.common.util;

import com.plum.admin.common.annotation.Log;
import lombok.experimental.UtilityClass;
import org.aspectj.lang.JoinPoint;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * TODO
 *
 * @author 冷言丶冷语
 * @version 1.0
 * @date 2020/9/11 10:19
 */
@UtilityClass
public class LogUtil {
    public Map<String,Object> getControllerMethod(JoinPoint point) throws Exception {
        Map<String,Object> param= new HashMap<>(16);
        // 获取连接点目标类名
        String targetName = point.getTarget().getClass().getName();
        // 获取连接点签名的方法名
        String methodName = point.getSignature().getName();
        //获取连接点参数
        Object[] args = point.getArgs();
        //根据连接点类的名字获取指定类
        Class targetClass = Class.forName(targetName);
        //获取类里面的方法
        Method[] methods = targetClass.getMethods();
        String title;
        Integer type;
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == args.length) {
                    title = method.getAnnotation(Log.class).title();
                    type=method.getAnnotation(Log.class).type().ordinal();
                    param.put("title",title);
                    param.put("type",type);
                    break;
                }
            }
        }
        return param;
    }
    /**
     * 获取堆栈信息
     *
     * @param throwable
     * @return
     */
    public String getStackTrace(Throwable throwable) {
        StringWriter sw = new StringWriter();
        try (PrintWriter pw = new PrintWriter(sw)) {
            throwable.printStackTrace(pw);
            return sw.toString();
        }
    }
}
